/**
 * put global state here
 */
import { State, Action, StateContext } from "@ngxs/store";

// actions
export namespace AppActions {
  export class UpdateBreadcrumb {
    static readonly type = "[AppActions] UpdateBreadcrumb";
    constructor(public breadcrumb: Breadcrumb[]) {}
  }

  export class InvalidateSession {
    static readonly type = "[AppActions] InvalidateSession";
  }

  export class ServiceStatus {
    static readonly type = "[AppActions] ServiceStatus";
    constructor(public status: string) {}
  }
}

export interface Breadcrumb {
  name: string;
  routerLink?: string;
}

// state-model and state
export interface AppStateModel {
  breadcrumb: Breadcrumb[];
  sessionStatus: number;
  serviceStatus: string;
}

@State<AppStateModel>({
  name: "app",
  defaults: {
    breadcrumb: [],
    sessionStatus: 0,
    serviceStatus: ""
  }
})
export class AppState {
  @Action(AppActions.UpdateBreadcrumb)
  updateBreadcrumb(
    ctx: StateContext<AppStateModel>,
    action: AppActions.UpdateBreadcrumb
  ) {
    ctx.patchState({ breadcrumb: action.breadcrumb });
  }

  @Action(AppActions.InvalidateSession)
  invalidateSession(ctx: StateContext<AppStateModel>) {
    ctx.patchState({ sessionStatus: ctx.getState().sessionStatus + 1 });
  }

  @Action(AppActions.ServiceStatus)
  showServiceStatus(
    ctx: StateContext<AppStateModel>,
    action: AppActions.ServiceStatus
  ) {
    ctx.patchState({ serviceStatus: action.status });
  }
}
